﻿using Micro.Core.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Micro.Core.Configs
{
    public class BaseDBConfig
    {
        private readonly DbConfig _dbConfig;
        public BaseDBConfig(DbConfig dbConfig)
        {
            if (dbConfig == null || dbConfig.DbOptions == null || dbConfig.DbOptions.Count == 0)
                throw new MicroException($"DbConfig未配置，nameof(BaseDBConfig)");
            _dbConfig =  dbConfig;
            (List<DbOption> allDbs, List<DbOption> slaveDbs) = MutiInitConn();
            this.AllDbs = allDbs;
            this.SlaveDbs = slaveDbs;
        }

        /// <summary>
        /// 全部库
        /// </summary>
        public List<DbOption> AllDbs= new List<DbOption>();

        /// <summary>
        /// 从库
        /// </summary>
        public List<DbOption> SlaveDbs = new List<DbOption>();


        private (List<DbOption>, List<DbOption>) MutiInitConn()
        {
            List<DbOption> listdatabase = _dbConfig.DbOptions.Where(i => i.Enabled).ToList();
            


            List<DbOption> listdatabaseSimpleDB = new List<DbOption>();//单库
            List<DbOption> listdatabaseSlaveDB = new List<DbOption>();//从库

            // 单库，且不开启读写分离，只保留一个
            if (!_dbConfig.CQRSEnabled && !_dbConfig.MutiDBEnabled)
            {
                if (listdatabase.Count == 1)
                {
                    return (listdatabase, listdatabaseSlaveDB);
                }
                else
                {
                    var dbFirst = listdatabase.FirstOrDefault(d => d.ConnId == _dbConfig.MainDB);
                    if (dbFirst == null)
                    {
                        dbFirst = listdatabase.FirstOrDefault();
                    }
                    if (dbFirst != null)
                        listdatabaseSimpleDB.Add(dbFirst);
                    return (listdatabaseSimpleDB, listdatabaseSlaveDB);
                }
            }
            // 读写分离，且必须是单库模式，获取从库
            else if (_dbConfig.CQRSEnabled && !_dbConfig.MutiDBEnabled)
            {
                if (listdatabase.Count > 1)
                {
                    listdatabaseSlaveDB = listdatabase.Where(d => d.ConnId != _dbConfig.MainDB).ToList();
                }
            }


            return (listdatabase, listdatabaseSlaveDB);
            //}
        }
    }
}
